<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <link href="../css/message.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script src="../js/jquery-3.3.1.min.js"></script>

</head>

<body>
<div id="myDropdown" class="dropdown-content">
    <div style="display: flex;flex-direction: column;">
        <label for="message-search" class="message-label">
            <input placeholder="搜索联系人" id="message-search" class="message-input">
            <img src="/zhihu1/imgs/message-imgs/search.png" style="margin-left: 15px;width: 15px;cursor: pointer"
                 id="message-search-img">
        </label>
        <div class="message-conent-class">
            <ul style="padding: 0;" id="list-message-ul">

            </ul>
        </div>
    </div>
    <div id="window" class="window_css">

    </div>
</div>
<script>
    let questionContent = null;
    let quill = null;
    //选择的目标图片
    let userImg2 = null;
    //当前用户id
    let userId = 0;
    //选择的目标用户
    let userId1 = 0;
    //当前用户图片
    let userImg = null;
    $(function () {
        selectUser();
    })

    function selectMessage() {
        $.ajax({
            async: true,
            url: "http://localhost:8080/zhihu1/message?ac=queryMessage",
            type: "post",
            data: {
                userId: userId
            },
            dataType: "json",
            success: function (data) {
                selectList(data)
            }
        })
    }

    <% Object username = session.getAttribute("username");%>

    function selectUser() {
        $.ajax({
            async: true,
            url: "http://localhost:8080/zhihu1/user?ac=selectUser",
            type: "post",
            data: {
                username: "<%=username %>"
            },
            dataType: "json",
            success: function (data) {
                userId = data.data[0].id;
                userImg = data.data[0].img;
                selectMessage();
            }
        })
    }

    function selectFollowMessage(){
        $.ajax({
            async: true,
            url: "http://localhost:8080/zhihu1/message?ac=queryFollowUserMessage",
            type: "post",
            data: {
                userId: userId
            },
            dataType: "json",
            success: function (data) {
                let questionData = data.data;
                let content = $("#follow-content");
                content.empty();

                for (let i = 0; i < questionData.length; i++) {
                    let question = questionData[i];
                    let questionCard = `
                    <li class="chatlist list-li-left">
                        <div class="block active" onclick="list(${question.id},'${question.user_name}','${question.img}')">
                        <div class="imgbx">
                            <img src="${question.img}" class="cover">
                        </div>
                        <div class="details">
                            <div class="list-head-follow">
                                <h4>${question.user_name}</h4>
                            </div>
                        </div>
                        </div>
                    </li>`;

                    let messageP = $('<div>').html(questionCard);
                    content.append(messageP);
                }
            }
        })
    }

    function selectList(data) {
        let questionData = data.data;
        let ulContent = $("#list-message-ul");
        ulContent.empty();
        // 构建最近联系和相互关注的内容
        questionContent = `
            <li class="list-li-left list-li" id="select-user-content" onclick="selectUserContent()">最近联系
                <img class="user-message-img list-message-img img-rotate" src="../imgs/menus-img/arrow-bottom.png">
            </li>
            <ul id="user-content" class="user-conent-class"></ul>
            <li class="list-li-left list-li" id="select-follow-content" onclick="selectFollowContent()">相互关注
                <img class="follow-message-img list-message-img follow-img-rotate" src="../imgs/menus-img/arrow-bottom.png">
            </li>
            <ul id="follow-content" class="user-conent-class"></ul>`;

        // 将最近联系和相互关注的内容插入到 ulContent
        ulContent.append(questionContent);
        let content = $("#user-content");

        // 构建 questionData 中的每个元素对应的 HTML 内容
        for (let i = 0; i < questionData.length; i++) {
            let question = questionData[i];
            let cleanContent = question.content.replace(/<.*?>/g, '');
            let questionCard = `
                    <li class="chatlist list-li-left">
                        <div class="block active" onclick="list(${question.user},'${question.user_name}','${question.img}')">
                            <div class="imgbx">
                                <img src="${question.img}" class="cover">
                            </div>
                            <div class="details">
                                <div class="listHead">
                                    <h4>${question.user_name}</h4>
                                    <p class="time">${question.create_time}</p>
                                </div>
                                <div class="message_p">
                                    <p>${cleanContent}</p>
                                </div>
                            </div>
                        </div>
                    </li>`;
            let messageP = $('<div>').html(questionCard);
            content.append(messageP);
        }
        selectFollowMessage();
    }

    function list(id, name, img) {
        if(questionContent == null){
            selectMessage();
        }
        $.ajax({
            async: true,
            url: "http://localhost:8080/zhihu1/message?ac=queryUserMessage",
            type: "post",
            data: {
                id, id,
                userId: userId
            },
            dataType: "json",
            success: function (data) {
                userId1 = id;
                userImg2 = img;
                let questionData = data.data;
                let content = $("#window");
                let questionCard = "";
                content.empty();
                let shujv = "";
                for (let i = 0; i < questionData.length; i++) {
                    let question = questionData[i];
                    if (question.user1_id == userId) {
                        shujv += `<li class="left">
                                    <img style="width:40px;height:40px" src="${userImg2}">
                                    <span>${question.content}</span>
                                </li>`;
                    } else if (question.user_id == userId) {
                        shujv += `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${question.content}</span>
                                </li>`;
                    }
                    questionCard = `<ul id="div-ul" class="m-ul">
                 ` + shujv + `
                </ul>`;
                }


                let bigDiv = `<h1>${name}</h1>
                        <div class="window_css_dialogue">
                        ` + questionCard + `
                        </div>
                         <div id="editor" class="editor"> </div>
                         <button class="button1" onclick="sending(${id})">发送</button>`;
                content.append(bigDiv);

                let toolbarOptions = [
                    ['image'],
                ];

                quill = new Quill('#editor', {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow',
                    placeholder: "请输入内容"
                });
                close();
                scrollHeight()
            }
        })
    }

    $("#message-search-img").on("click", function () {
        let val = $("#message-search").val();
        $.ajax({
            async: true,
            url: "http://localhost:8080/zhihu1/message?ac=queryMessageList",
            type: "post",
            data: {
                userId: userId,
                username: val
            },
            dataType: "json",
            success: function (data) {
                questionContent = null;
                let questionData = data.data;
                let content = $("#list-message-ul");
                content.empty();
                for (let i = 0; i < questionData.length; i++) {
                    let question = questionData[i];
                    let cleanContent = question.content.replace(/<.*?>/g, '');
                    let questionCard = `
                    <li class="chatlist list-li-left">
                        <div class="block active" onclick="list(${question.user},'${question.user_name}','${question.img}')">
                            <div class="imgbx">
                                <img src="${question.img}" class="cover">
                            </div>
                            <div class="details">
                                <div class="listHead">
                                    <h4>${question.user_name}</h4>
                                    <p class="time">${question.create_time}</p>
                                </div>
                                <div class="message_p">
                                    <p>${cleanContent}</p>
                                </div>
                            </div>
                        </div>
                    </li>`;
                    let messageP = $('<div>').html(questionCard);
                    content.append(messageP);
                }
            }
        })

    })

    function sending(id) {
        window.parent.prohibition();
        let content = $(".ql-editor").html();
        if (content != "<p><br></p>") {
            $.ajax({
                async: true,
                url: "http://localhost:8080/zhihu1/message?ac=addMessage",
                type: "post",
                data: {
                    id, id,
                    userId: userId,
                    content: content,
                },
                dataType: "json",
                success: function (data) {
                    let text = {
                        content: content,
                        toUserId: id,
                        id: userId
                    };
                    if(data.data == false){
                        let right = `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${content}</span>
                                    <i title="未互相关注前，不能连续发两条!" class="fa fa-exclamation-circle" style="color:red;font-size:25px;margin:0 10px;"></i>
                                </li>`;
                        $("#div-ul").append(right);
                        $(".ql-editor").html("");
                        scrollHeight();
                    }else {
                        socket.send(JSON.stringify(text));
                        let right = `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${content}</span>
                                </li>`;
                        $("#div-ul").append(right);
                        $(".ql-editor").html("");
                        scrollHeight();
                    }
                }
            })
        }
    }

    function scrollHeight() {
        var container = $('.window_css_dialogue');
        // 设置滚动条位置为最底部
        container.scrollTop(container[0].scrollHeight);
    }

    function selectUserContent(){
        if($("#user-content").css("height") == '0px'){
            $(".img-rotate").css("transform","rotate(0)");
            $("#follow-content").css("height","0px")
            $("#user-content").css("height","100%")
            $(".follow-img-rotate").css("transform","rotate(-90deg)");
        }else {
            $(".img-rotate").css("transform","rotate(-90deg)");
            $("#user-content").css("height","0px")
        }
    }

    function selectFollowContent(){
        if($("#follow-content").css("height") == '0px'){
            $(".follow-img-rotate").css("transform","rotate(0)");
            $("#user-content").css("height","0px")
            $("#follow-content").css("height","100%")
            $(".img-rotate").css("transform","rotate(-90deg)");
        }else {
            $(".follow-img-rotate").css("transform","rotate(-90deg)");
            $("#follow-content").css("height","0px")
        }
    }

    $("html").on("click", function (event) {
        window.parent.$("#pmyDropdown").css("display", "none");
        window.parent.close()
    })

    const wsuri = 'ws://localhost:8080/zhihu1/websocket';//ws地址
    let socket = new WebSocket(wsuri);

    socket.addEventListener('open', function () {
        console.log("连接成功")
    })

    socket.addEventListener('message', function (event) {
        let data = JSON.parse(event.data);
        if (data.id == userId1 && data.toUserId == userId) {
            let left = `<li class="left">
                    <img style="width:40px;height:40px" src="${userImg2}">
                    <span>${data.content}</span>
                </li>`;
            $("#div-ul").append(left);
            scrollHeight();
        }
    });

    socket.addEventListener('error', function (error) {
        console.error('WebSocket 发生错误:', error);
    });

    socket.addEventListener('close', function (event) {
        if (event.wasClean) {
            console.log(`连接关闭，状态码：${event.code}, 原因：${event.reason}`);
        } else {
            console.error('连接异常断开');
        }
    });

</script>

</body>

</html>